import os
from datetime import datetime
import socket


def is_port_in_use(host, port):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        try:
            s.bind((host, port))
            s.close()  # 立即关闭套接字以释放端口
            return False  # 端口未被占用
        except socket.error:
            # 端口被占用
            return True


def folders_by_file(directory):
    # 获取目录下所有文件夹
    folders = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f)) and f.endswith('.bin')]
    return folders


# 提取日期时间并转换为时间戳的函数
def extract_timestamp(file_name):
    # 使用正则表达式提取日期时间部分，这里直接根据格式硬编码提取，因为格式固定
    filename = os.path.basename(file_name)
    file_name = filename.split(".")[0]
    date_str = file_name.split("_")[1]
    print(date_str)
    # 将日期时间字符串转换为datetime对象
    dt_obj = datetime.strptime(date_str, "%Y-%m-%d-%H-%M")
    # 转换为时间戳（注意：这里返回的是浮点数类型的时间戳）
    timestamp = dt_obj.timestamp()
    return timestamp


def sort_folders_by_timestamp(folders, id):
    List = []
    for folder in folders:
        filename = os.path.basename(folder)
        if filename.strip("_")[0] == str(id):
            List.append(folder)
    # 根据时间戳排序文件列表
    sorted_files = sorted(List, key=extract_timestamp)
    return sorted_files


def get_folders(directory, id):
    folders = folders_by_file(directory)
    id_folders = sort_folders_by_timestamp(folders, id)
    for i in range(len(id_folders)):
        id_folders[i] = os.path.join(directory, id_folders[i])
    return id_folders


import json
import redis


def get_status():
    pool = redis.ConnectionPool(host='10.100.12.58', port=6379, db=11, decode_responses=False)
    r = redis.Redis(connection_pool=pool)
    names = r.hgetall("deviceInfo")
    result = {}
    for name in names:
        value = r.hget("deviceInfo", name)
        # print(type(value),value.decode().replace("'", '"'))
        v = value.decode().replace("'", '"')
        data = json.loads(v)
        result[name.decode()] = data

def get_set(key):
    pool = redis.ConnectionPool(host='10.100.12.58', port=6379, db=11, decode_responses=False)
    r = redis.Redis(connection_pool=pool)
    name = r.get(key)
    return int(name.decode())


def send_redis_set(k, v):
    pool = redis.ConnectionPool(host='10.100.12.58', port=6379, db=11, decode_responses=False)
    r = redis.Redis(connection_pool=pool)
    r.set(k, v)


def send_redis_hset(k1, k2, v):
    pool = redis.ConnectionPool(host='10.100.12.58', port=6379, db=11, decode_responses=False)
    r = redis.Redis(connection_pool=pool)
    r.hset(k1, k2, v)

if __name__ == '__main__':
    get_set("time_diff")
